package com.ad_hccm.interceptor;

import com.ad_hccm.controller.Code;
import com.ad_hccm.domain.User;
import com.ad_hccm.exception.TokenAuthException;
import com.ad_hccm.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.el.parser.Token;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * TODO 拦截器 验证token
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    TokenUtil tokenUtil;
    @Value("${token.privateKey}")
    private String privateKey;
    @Value("${token.yangToken}")
    private Long yangToken;
    @Value("${token.oldToken}")
    private Long oldToken;
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(!(handler instanceof HandlerMethod)){
            // 不是访问方法
            return true;
        }
        String token = request.getHeader("token");
        if(token == null || "".equals(token.trim())){
            return false;
        }
        Map<String,String> map = tokenUtil.parseToken(token);
        String userId = map.get("userId");
        String userRole = map.get("userRole");
        //token使用时长
        long timeOfUse = System.currentTimeMillis() - Long.parseLong(map.get("timeStamp"));
        if(timeOfUse < yangToken) {
        }else if(timeOfUse > yangToken && timeOfUse < oldToken){ //快过期了，刷新一下
            response.setHeader("token",tokenUtil.getToken(userId,userRole));
        }else{ //token过期
            throw new TokenAuthException(Code.Token_ERR, "token err");
        }
        //权限匹配
        if("user".equals(userRole) && handler.toString().matches("search")==false){
            User user = userService.getByAccount(userId);
            if(user!=null && user.getRole().equals("user")) return true;
            return false;
        }else if("admin".equals(userRole)){
            User user = userService.getByAccount(userId);
            if(user!=null && user.getRole().equals("admin")) return true;
            return false;
        }
        return false;
    }
}
